package com.linkoog.devtools.code_generator.wizard.model;


import javax.swing.*;
import java.awt.*;
import java.util.EventObject;


public class ModelTreeTableCellEditor extends DefaultCellEditor {

    private JTree edit_tree;

    public ModelTreeTableCellEditor() {
        super(new JTextField());
        this.setClickCountToStart(2);
    }

    public boolean isCellEditable(EventObject anEvent) {
        return delegate.isCellEditable(anEvent);
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        if (edit_tree == null){
            ModelJsonTreeTable treeTable = (ModelJsonTreeTable)table;
            edit_tree = treeTable.getTree();
        }
        final JTextField field = (JTextField)super.getTableCellEditorComponent(table, value, isSelected, row, row);
        if (value instanceof ModelJsonTreeTable.ItemInfo){
            ModelJsonTreeTable.ItemInfo nodeData = (ModelJsonTreeTable.ItemInfo) value;
            field.setText(nodeData.getName());
        }
        return field;
    }

    /**
     *  输入entry键，正常结束编辑时，被调用
     */
    public boolean stopCellEditing(){
        doStopEditing();
        return true;
    }

    /**
     *  失去焦点时，非正常结束编辑时，被调用
     */
    public void cancelCellEditing() {
        doStopEditing();
    }

    private void doStopEditing() {
        if (edit_tree == null){
            return;
        }

        Object lastSelectedPathComponent = edit_tree.getLastSelectedPathComponent();
        if (lastSelectedPathComponent instanceof ModelJsonTreeTable.ItemInfo){
            ModelJsonTreeTable.ItemInfo node = (ModelJsonTreeTable.ItemInfo) lastSelectedPathComponent;
            String new_value = getCellEditorValue().toString();
            node.setName(new_value);
        }

        edit_tree.setEditable(false);
        fireEditingCanceled();
    }

}
